package com.mzy.concurrent;

/**
 * @Author: mizy3
 * @Date: 2024/08/20/下午3:35
 * @Description:
 */
public class 交替打印奇偶数 {

   /* public static final Object lock = new Object();
    public static boolean odd = false;

    public static void main(String[] args) {
        new Thread(() -> {
            for (int i = 1; i <= 100; i += 2) {
                synchronized (lock) {
                    while (odd) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println(i);
                    odd = true;
                    lock.notifyAll();
                }
            }
        }).start();

        new Thread(() -> {
            for (int i = 2; i <= 100; i += 2) {
                synchronized (lock) {
                    while (!odd) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println(i);
                    odd = false;
                    lock.notifyAll();
                }
            }
        }).start();

    }*/


    public static boolean odd = false;
    public static final Object lock = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (lock){
                for (int i = 1; i <= 100 ; i+=2) {
                    while (odd){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println(i);
                    odd = true;
                    lock.notifyAll();
                }
            }
        }).start();

        new Thread(() -> {
            synchronized (lock){
                for (int i = 2; i <= 100 ; i+=2) {
                    while (!odd){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println(i);
                    odd = false;
                    lock.notifyAll();
                }
            }
        }).start();
    }
}
